#include "utils/socket.h"
#include <iostream>

using namespace cox;

void testTcpClient() {
	// 创建TCP socket
	Socket clientSocket(Socket::TCP);
	if (clientSocket.getFd() < 0) {
		std::cerr << "创建客户端Socket失败" << std::endl;
		return;
	}

	// 连接服务器（假设服务器在本地8080端口）
	NetAddr serverAddr("127.0.0.1", 8080);
	if (!clientSocket.connect(serverAddr, TimeVal(5, 0))) { // 超时5秒
		std::cerr << "连接服务器失败，错误码：" << clientSocket.getError() << std::endl;
		return;
	}
	std::cout << "成功连接到服务器" << std::endl;

	// 接收服务器欢迎消息
	char recvBuf[1024] = {0};
	if (clientSocket.canRecv(TimeVal(3, 0))) { // 等待3秒接收
		long long recvLen = clientSocket.recv(recvBuf, 1023);
		if (recvLen > 0) {
			std::cout << "收到服务器消息：" << recvBuf << std::endl;
		}
	}

	// 向服务器发送消息
	const char *sendMsg = "你好，服务器！";
	long long   sendLen = clientSocket.send(sendMsg, strlen(sendMsg));
	if (sendLen < 0) {
		std::cerr << "发送失败" << std::endl;
	} else {
		std::cout << "发送成功，长度：" << sendLen << std::endl;
	}
}

// 编译: g++
int main() {
	testTcpClient();
	return 0;
}
